<template>
  <div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <h1>管理员登录</h1>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: 'root',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 12, message: '长度在 3 到 12 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  beforeCreate() {		//在页面创建之前设置body的背景色
    document.querySelector('body').setAttribute('style', 'background:lightgray')
  },
  beforeDestroy() {		//在页面销毁之前移除body的属性，目的是设置的颜色只对当前页面有效
    document.querySelector('body').removeAttribute('style')
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('开始进行登录')
          let url = 'http://localhost:9081/admins/login'
          console.log('请求路径...')
          console.log(url)
          console.log('请求参数...')
          console.log(this.ruleForm)
          let formData = this.qs.stringify(this.ruleForm)
          console.log('处理后的请求参数')
          console.log(formData)
          this.axios.post(url,formData).then(response=>{
            console.log('接收到服务器返回的数据')
            console.log('response的参数：')
            console.log(response)
            let responseBody = response.data
            let jwt = responseBody.data
            console.log('responseBody的参数：')
            console.log(responseBody)
            if(responseBody.state == 20000){
              this.$message.success("登录成功")
              console.log('登录成功，jwt的参数：')
              console.log(jwt)
              localStorage.setItem('jwt',jwt);
              //测试
              /*
              let localJwt = localStorage.getItem('jwt')
              console.log('从localStorage获取jwt：' + localJwt)
              */
            }else {
              this.$message.error(responseBody.message)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scope>
  /*body{*/
  /*  background-color: aqua;*/
  /*}*/
  .el-form>h1{
    text-align: center;
  }
</style>